import { defineStore } from 'pinia'
import { message } from 'ant-design-vue'
import { getUserDetail, login, logout } from '@/apis/account'
import { removeToken, removeUser, setToken, setUser, getUser } from '@/utils/token'
import md5 from 'md5'
// TODO:fix this
// interface UserState { }
export const useUserStore = defineStore({
  id: 'users',
  state: (): any => ({
    user: null,
    permissions: null,
    token: ''
  }),
  getters: {
    getUser (): any {
      return this.user
    },
    getPermissions (): any {
      return this.permissions
    }
  },
  actions: {
    handleLogin (paramter) {
      return new Promise((resolve, reject) => {
        paramter.password = md5(paramter.password)
        login(paramter).then((res: any) => {
          if (res.code !== 200) {
            message.error(res.err)
            resolve({})
          } else {
            // user = {
            //   avatar_url: '',
            //   id: '',
            //   sys_role: '',
            //   token: '',
            //   username: ''
            // }
            const { info } = res
            const token = info.token
            this.token = token
            // 设置 token
            this.user = info
            setUser(info)
            setToken(token)
            resolve(info)
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogout (): Promise<any> {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          // 清除 Cookie 中的 token
          removeToken()
          removeUser()
          this.user = null
          this.permissions = null
          this.token = ''
          setUser(null)
          resolve(null)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取用户信息
    getUserInfo () {
      return new Promise((resolve, reject) => {
        getUserDetail().then(res => {
          if (res.code === 200) {
            const { info } = res
            // 操作用户信息
            const user: any = getUser() || {}
            Object.keys(info).forEach(key => {
              user[key] = info[key]
            })
            this.user = user
            setUser(user)
            const defaultPermissions: string[] = []
            const rolePermissionsList = defaultPermissions.concat([info.sys_role])
            window.localStorage.setItem('ROLE_PERMISSIONS_LIST', JSON.stringify(rolePermissionsList))
            // 操作用户信息
            this.permissions = rolePermissionsList
            resolve(user)
          } else {
            resolve(null)
          }
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
})

// Need to be used outside the setup
export function setupStore (store: any) {
  return useUserStore(store)
}
